package com.dongge.action;

import com.dongge.entity.Department;
import com.dongge.entity.Role;
import com.dongge.entity.User;
import com.dongge.service.DepartmentService;
import com.dongge.service.RoleService;
import com.dongge.service.UserService;
import com.opensymphony.xwork2.ActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2015/11/3.
 */
@Controller
@Scope("prototype")
public class UserAction extends BaseAction<User> implements CURDAction{

    private long[] roleIds;
    private long departmentId;

    @Resource
    private UserService userService;
    @Resource
    private DepartmentService departmentService;

    @Resource
    private RoleService roleService;

    public long[] getRoleIds() {
        return roleIds;
    }

    public void setRoleIds(long[] roleIds) {
        this.roleIds = roleIds;
    }

    public long getDepartmentId() {
        return departmentId;
    }

    public void setDepartmentId(long departmentId) {
        this.departmentId = departmentId;
    }

    public String add() {//department怎么过来

        Department department = departmentService.get(departmentId);
        System.out.println(new Date());
        model.setCreateTime(new Date());
        model.setDepartment(department);
        userService.save(model);
        userService.updateUserRoleById(model.getId(),roleIds);
        return "toList";
    }

    public String addPrepare() {
        List<Department> departments = departmentService.getAll();
        ActionContext.getContext().put("departments",departments);
        List<Role> roles = roleService.getAll();
        ActionContext.getContext().put("roles", roles);
        return "addPrepare";
    }

    public String delete() {
        userService.delete(model.getId());
        return "toList";
    }

    public String edit() {
        Department department = departmentService.get(departmentId);
        model.setDepartment(department);
        userService.update(model);
        userService.updateUserRoleById(model.getId(),roleIds);
        return "toList";
    }

    public String editPrepare() {
        List<Department> departments = departmentService.getAll();
        ActionContext.getContext().put("departments",departments);
        User user = userService.get(model.getId());
        ActionContext.getContext().getValueStack().push(user);
        if(user.getDepartment()!=null){
            departmentId = user.getDepartment().getId();
        }
        roleIds = userService.getUserRoleIdsById(model.getId());
        List<Role> roles = roleService.getAll();
        ActionContext.getContext().put("roles", roles);
        return "editPrepare";
    }

    public String list() {
        List<User> users = userService.getAll();
        ActionContext.getContext().put("users",users);
        return "list";
    }
}
